﻿using CommandService;
using Entity.FrameEntity;
using Entity;
using SysFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tools;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;


namespace BLL
{
    public class QualityBLL : SysFramework.PubMethod
    {
        Commands cmd;
        ReturnResult rsl;
        OperateModel oper;
        List<OperateModel> operList;
        public QualityBLL()
        {
            cmd = new Commands();
        }
        /// <summary>
        /// 添加质检记录
        /// </summary>
        /// <param name="barCode"></param>
        /// <param name="datas"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult AddCheckRecords(string barCode,string datas, string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                operList=new List<OperateModel> ();
                if (string.IsNullOrWhiteSpace(barCode))
                {
                    rsl.Message = "关联条码不能为空";return rsl;
                }
                var json=JsonConvert.DeserializeObject<JObject>(datas);
                bool first = true;
                List<Dictionary<string, string>> msgList = new List<Dictionary<string, string>>();
                #region 记录主数据
                oper = new OperateModel();
                DbCheckRecordsMain checkMain = new DbCheckRecordsMain();
                DbCheckRecordsSub checkSub;
                string crCode = "";
                checkMain.crCode = crCode;
                checkMain.isdel = 0;
                checkMain.hDate=getNowDate();
                checkMain.checkUser = json["user-title"].ToString();
                checkMain.chResult = json["chResult"].ToString();
                checkMain.createtime = getNow();
                checkMain.createuser= userCode;
                checkMain.checkBar= barCode;
                if (string.IsNullOrWhiteSpace(json["id"].ToString()) || json["id"].ToString() == "0")
                {
                    crCode = getTimeString();
                    checkMain.crCode = crCode;
                    oper.Types=OperateModel.OperateType.Add;
                }
                else
                {
                    crCode = json["crCode"].ToString();
                    checkMain.id = int.Parse(json["id"].ToString());
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    first = false;
                }
                oper.Data = checkMain;
                operList.Add(oper);
                #endregion
                string sql = "select * from jy_CheckRecords_sub where crCode='"+ crCode +"'";
                var sTable = cmd.GetDataTable(sql);

                sql = "select isnull(parValue,'') value from sys_parameters_info where parCode='checkUser'";
                var parTable=cmd.GetDataTable(sql);
                string users = "";
                if (parTable.Rows.Count > 0 )
                {
                    users=parTable.Rows[0][0].ToString();
                }
                #region 子表
                foreach (JProperty obj in json.Properties())
                {
                    if (obj.Name.Contains("title"))
                    {
                        continue;
                    }
                    if (obj.Name.Contains("result") && obj.Value.ToString() == "")
                    {
                        rsl.Message = "请选择结果"; return rsl;
                    }
                    var dr = sTable.Select("jyCode='"+ obj.Name + "'");
                    checkSub = new DbCheckRecordsSub();
                    oper = new OperateModel();
                    if (dr.Length > 0)
                    {
                        checkSub.id =dr[0]["id"].ToString();
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "id";
                    }
                    else
                    {
                        if (obj.Value == null || string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            continue;
                        }
                        checkSub.id = Guid.NewGuid().ToString().Replace("-", "");
                        checkSub.crCode = crCode;
                        checkSub.jyCode = obj.Name;
                        oper.Types = OperateModel.OperateType.Add;
                    }
                    checkSub.jyContents = obj.Value.ToString();
                    oper.Data = checkSub;
                    operList.Add(oper);
                    if (first)
                    {
                        if (obj.Name.Contains("result") && obj.Value.ToString() == "0")
                        {
                            var cArr = obj.Name.ToString().Split('-');
                            string jcName = string.Format("{0}-{1}-title", cArr[0], cArr[1]);
                            string nr = string.Format("{0}-{1}-nr", cArr[0], cArr[1]);
                            string memo = string.Format("{0}-{1}-memo", cArr[0], cArr[1]);
                            var d_dic = new Dictionary<string, string>();
                            d_dic["tip01"] = "检测项：" + json[jcName].ToString();
                            d_dic["tip02"] = "检测内容：" + json[nr].ToString();
                            d_dic["tip03"] = "备 注:" + json[memo].ToString();
                            msgList.Add(d_dic);
                        }
                    }
                
                     
                   
                }
                #region 不合格内容发送消息提醒
                if (msgList.Count>0 && !string.IsNullOrWhiteSpace(users))
                {
                        var arr = users.Split(',');
                        foreach (string u in arr)
                        {
                            if (!string.IsNullOrWhiteSpace(u))
                            {
                                AppBLL appBLL = new AppBLL();
                                var dic = new Dictionary<string, object>();
                                dic["businessType"] = "quaCheck";
                                dic["businessCode"] = crCode;
                                dic["toUser"] = u;
                                dic["memo"] = "质检消息提醒";
                                dic["contents"] = "质检消息提醒，请及时处理";
                                dic["datas"] = msgList;
                                appBLL.CreateMsgInfo(dic,userCode,ref operList);
                            }

                        }
                }

                #endregion
                #endregion
               
                #region 改变条码状态
                if (first)
                {
                    DbProductBarCode bar = new DbProductBarCode();
                    bar.barCode = barCode;
                    bar.barStatus = "need-in";//质检完成，状态默认为待入库
                    oper = new OperateModel();
                    oper.Data = bar;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "barCode";
                    operList.Add(oper);
                }
                #endregion
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 条码不检验方法
        /// </summary>
        /// <param name="barCodes"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult NoCheckData(string barCodes,string userCode)
        {
            try
            {
                operList = new List<OperateModel>();
                if (string.IsNullOrWhiteSpace(barCodes))
                {
                    rsl.Message = "检验条码信息获取失败";return rsl;
                }
                var bArr=barCodes.Split(',');
                for(int i=0;i<bArr.Length;i++)
                {
                    if (!string.IsNullOrWhiteSpace(bArr[i]))
                    {
                        #region 记录主数据
                        DbCheckRecordsMain checkMain = new DbCheckRecordsMain();
                        DbCheckRecordsSub checkSub;
                        string crCode = getTimeString()+i.ToString();
                        checkMain.crCode = crCode;
                        checkMain.isdel = 0;
                        checkMain.chResult = "";
                        checkMain.hDate = getNowDate();
                        checkMain.checkUser = userCode;
                        checkMain.chResult = "2";
                        checkMain.createtime = getNow();
                        checkMain.createuser = userCode;
                        checkMain.checkBar = bArr[i];
                        oper = new OperateModel();
                        oper.Data = checkMain;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                        #endregion

                        #region 改变条码状态
                        DbProductBarCode bar = new DbProductBarCode();
                        bar.barCode = bArr[i];
                        bar.barStatus = "need-in";//质检完成，状态默认为待入库
                        oper = new OperateModel();
                        oper.Data = bar;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "barCode";
                        operList.Add(oper);
                        #endregion
                    }

                }
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult getCheckRecordList(string pageIndex, string pageSize, string condition, ref string pageCount)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }

         
                sb.Append(" isdel=0 ");
                sb = CreateSelectCondition(sb, condition, "gxCode;barStatus");
                var list = cmd.PageList("V_jy_CheckRecordMain", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i]["chResult"].ToString() == "1")
                    {
                        list[i]["resultName"] = "合格";
                    }
                    else if (list[i]["chResult"].ToString() == "0")
                    {
                        list[i]["resultName"] = "不合格";
                    }
                    else if (list[i]["chResult"].ToString() == "2")
                    {
                        list[i]["resultName"] = "不检验";
                    }
                    else
                    {
                        list[i]["resultName"] = "未知";
                    }
                     
                }
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 根据检测编码获取检测数据实体
        /// </summary>
        /// <param name="crCode"></param>
        /// <returns></returns>
        public ReturnResult GetCheckRecordByCode(string crCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select *,checkUser as 'user-title' from  jy_CheckRecords_main where crCode='" + crCode +"'");
                var mTable = cmd.GetDataTable(sb.ToString());
                sb.Clear();
                sb.Append("select * from jy_CheckRecords_sub where crCode='"+ crCode +"'");
                var sTable = cmd.GetDataTable(sb.ToString());
                Dictionary<string, string> dic = new Dictionary<string, string>();
                for (int i = 0; i < mTable.Columns.Count; i++)
                {
                    if (!dic.ContainsKey(mTable.Columns[i].ColumnName))
                    {
                        if (mTable.Rows[0][mTable.Columns[i].ColumnName] != null && !string.IsNullOrWhiteSpace(mTable.Rows[0][mTable.Columns[i].ColumnName].ToString()))
                        {
                            dic[mTable.Columns[i].ColumnName] = mTable.Rows[0][mTable.Columns[i].ColumnName].ToString();
                        }
              
                    }
                }
                foreach (DataRow r in sTable.Rows)
                {
                    if (!dic.ContainsKey(r["jyCode"].ToString()))
                    {
                        if (r["jyContents"] != null && !string.IsNullOrWhiteSpace(r["jyContents"].ToString()))
                        {
                            dic[r["jyCode"].ToString()] = r["jyContents"].ToString();
                        }

                    }
                }
                rsl.Result = true;
                rsl.Data=dic;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
}
